// @ts-nocheck
import { IPublicTypeCompositeValue } from '@alilc/lowcode-types';
import { JSONValue } from '../../editor/types/value.type';
import { ITypeEntityField } from '../types';

export const getStateDefaultValue = (fields: ITypeEntityField[], allRequired?: boolean) => {
  const state: Record<string, any> = {};
  fields.forEach((field) => {
    try {
      state[field.name] = transformFieldValue(field, allRequired);
      // console.log('state[field.name]: ', field.name, state[field.name]);
    } catch (e) {
      throw new Error(`字段：${field.name} 默认值解析错误`);
    }
  });
  // 转换默认值
  return getPureValue(state);
};

export const transformFieldValue = (field: ITypeEntityField, allRequired?: boolean) => {
  const { type, isArray, fields } = field;
  const value = transformValue(
    type,
    field.default,
    isArray,
    allRequired === true || field.required,
  );
  // console.log('[transformValue 22] ', field.default, type, isArray, value);
  if (!field.default && fields?.length > 0) {
    const item = getStateDefaultValue(fields);
    return isArray ? [] : item;
  }
  return value;
};

/**
 * 将字符串类型数据转换为对应类型
 */
export const transformValue = (
  type: ITypeEntityField['type'],
  value: IPublicTypeCompositeValue,
  isArray?: boolean,
  required?: boolean,
) => {
  if (isArray) {
    // console.log('[transformValue 1] ', type, value, typeof value, 'required: ', required);
    if (value) {
      if (typeof value === 'string') {
        return JSON.parse(value);
      } else if (typeof value === 'object') {
        return value;
      }
    } else {
      return !required ? [] : undefined;
    }
  }
  if (type === 'string') {
    if (value) {
      return String(value);
    }
    if (!required) {
      return '';
    }
  }
  if (type === 'number') {
    if (typeof value !== 'undefined' && value !== '') {
      return Number(value);
    } else if (!required) {
      return 0;
    }
  }
  if (type === 'boolean') {
    if (typeof value === 'boolean') {
      return value;
    } else if (!required) {
      return false;
    }
  }
  if (type === 'Date') {
    if (value) {
      // 处理日期字符串
      const dateStr = String(value);
      // 检查是否是有效的日期格式（YYYY-MM-DD）或日期时间格式（YYYY-MM-DD HH:mm:ss）
      if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
        // 纯日期格式
        return new Date(dateStr + ' 00:00:00');
      } else if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(dateStr)) {
        // 日期时间格式
        return new Date(dateStr);
      }
    }
    if (!required) {
      return new Date();
    }
  }
  if (type === 'object') {
    if (value && typeof value === 'string') {
      try {
        return JSON.parse(value);
      } catch (e) {
        return {};
      }
    } else {
      return typeof value === 'object' ? value : !required ? {} : undefined;
    }
  }
  if (isArray && !value) {
    return !required ? [] : undefined;
  }
  return value;
};

export const getPureValue = <T>(value: T): Record<string, any> => {
  const _value = value;
  const __enable = (value as any)?.__enable;
  if (__enable) {
    Object.keys(value).forEach((key) => {
      if (!__enable.includes(key)) delete _value[key];
    });
    delete (_value as any)?.__enable;
  }
  return value as Record<string, any>;
};

export const parseJson = (value: string): JSONValue => {
  if (typeof value === 'object') return value;
  try {
    return JSON.parse(value);
  } catch (error) {
    return undefined;
  }
};
